package com.leyou.gateway.filter;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class LoginFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取登录状态，jwtUtils.parse(String token)

        ServerHttpRequest request = exchange.getRequest();

        // 2.获取cookie
        HttpCookie cookie = request.getCookies().getFirst("LY_TOKEN");


        //没有cookie表示肯定没有登录，直接放行
        if (null == cookie) {
            chain.filter(exchange);
        }

        try {
            // 3.校验token是否有效
            String token = cookie.getValue();
            Payload payload = jwtUtils.parseJwt(token);

            //没有问题要刷新时间

            String key = payload.getUserDetail().getUsername();

            //更新过期时间
            this.redisTemplate.expire(key, 30, TimeUnit.MINUTES);

            log.info("登录有效期刷新成功");

        } catch (Exception e) {
            //登录有问题直接放行
            chain.filter(exchange);
        }

        // 5.放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        // 登录拦截，可以采用最高优先级！，在所有的过滤器中最优先执行
        return HIGHEST_PRECEDENCE;
    }
}
